
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
import org.fusesource.jansi.AnsiConsole;

public class CadastroHospital {

	public static void cahosp() {
		AnsiConsole.out.print("\u001b[2J");
		Scanner dados = new Scanner(System.in);
		short x=1;
		String hosp="", cnpj="", id="";
		boolean erro;
		System.out.println("___________________________________Hemouna______________________________________");
		System.out.println("____________________________Cadastros - Hospital________________________________");
		System.out.println("\n\n\n");
		try{
			Class.forName("org.hsqldb.jdbcDriver"); 	    
			Connection con = DriverManager.getConnection("jdbc:hsqldb:file:Banco/BD", "sa", "");
			Statement stm = con.createStatement(); 
			while (x == 1){
				System.out.print("CNPJ (somente numeros): ");
				erro = true;
				while (erro == true){
					cnpj = dados.next();
					if (cnpj.length() == 14){
						erro = false;
					} else {
						System.out.println("CNPJ invalido. Informe um valido.");
					}
					if (erro == false){
						ResultSet rs = stm.executeQuery("SELECT * FROM hospital where cnpj="+cnpj);
						while (rs.next()){
							id = rs.getString("cnpj");
						}
						if (id.equals(cnpj)){
							System.out.println("Este hospital ja esta cadastrado. Informe outro.");
							erro = true;
						} else {
							break;
						}
					}
				}
				dados.nextLine();
				System.out.print("\nNome do hospital: ");
				hosp = dados.nextLine();
		
				stm.execute("INSERT INTO HOSPITAL VALUES('"+cnpj+"','"+hosp+"')");
					
				System.out.printf("\n+------------------------------------------------------------------------------+");
				System.out.printf("|                      Cadastro realizado com sucesso                          |");
				System.out.printf("+------------------------------------------------------------------------------+");
				System.out.println("\n\nCadastrar outro hospital? 1-Sim ou 2-Nao");
				x = dados.nextShort();
				System.out.print("\n\n");
				dados.nextLine();
			}
			stm.execute("SHUTDOWN");
		}catch(ClassNotFoundException e){
		    System.out.println("Erro ao carregar o driver JDBC. ");
		}catch(Exception e){
		    System.out.println("Erro de SQL: "+e);
		    e.printStackTrace();
		}
		MenuADM.MeADM();
	}

}
